﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using XData.WebApp.Models;

namespace XData.Web.Mvc.Controllers
{
    [Authorize]
    public class AccountController : Controller
    {
        [AllowAnonymous]
        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }
            if (WebSecurity.Login(model))
            {
                return RedirectToLocal(returnUrl);
            }

            ModelState.AddModelError("", "The user name or password is incorrect");
            return View(model);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Logout()
        {
            WebSecurity.Logout();
            return RedirectToAction("Index", "Home");
        }

        private ActionResult RedirectToLocal(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }

        public ActionResult ChangePassword()
        {
            return View();
        }

        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid && WebSecurity.ChangePassword(model))
            {
                return RedirectToAction("ChangePasswordSuccessful");
            }

            ModelState.AddModelError("", "The current password is incorrect");

            return View(model);
        }

        public ActionResult ChangePasswordSuccessful()
        {
            return View();
        }

        //@Html.Action("Name","Account")
        public ActionResult Name()
        {
            string name = WebSecurity.User.Element("UserName").Value;
            return Content(name);
        }


    }
}